package com.xinke.query.model.typeHandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.xinke.query.model.entity.QueryJsonParams;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

// 声明此处理器映射的Java类型（UserInfo）和JDBC类型（JSON）
@MappedTypes(QueryJsonParams.class)
@MappedJdbcTypes(JdbcType.OTHER)
public class JsonTypeHandler2 extends BaseTypeHandler<QueryJsonParams> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 注册Java 8时间模块，支持LocalDateTime
        JavaTimeModule module = new JavaTimeModule();

        // 配置LocalDateTime的序列化/反序列化格式（与JSON中的格式匹配）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
        module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));

        objectMapper.registerModule(module);

        // 关闭序列化时的日期检查（可选，根据需求配置）
        //objectMapper.disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    }

    // 插入时：将Java对象转为JSON字符串写入数据库
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, QueryJsonParams parameter, JdbcType jdbcType) throws SQLException {
        try {
            String json = objectMapper.writeValueAsString(parameter);
            ps.setString(i, json);
        } catch (JsonProcessingException e) {
            throw new SQLException("Failed to convert QueryJsonParams to JSON string", e);
        }
    }

    // 查询时：从数据库读取JSON字符串转为Java对象
    @Override
    public QueryJsonParams getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        return json != null ? parseJson(json) : null;
    }

    @Override
    public QueryJsonParams getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return json != null ? parseJson(json) : null;
    }

    @Override
    public QueryJsonParams getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return json != null ? parseJson(json) : null;
    }

    // 解析JSON字符串为UserInfo对象
    private QueryJsonParams parseJson(String json) {
        try {
            return objectMapper.readValue(json, QueryJsonParams.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to parse JSON string to QueryJsonParams", e);
        }
    }
}
